home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6348 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: mozo.cc.purdue.edu!not-for-mail
  2. From: emurac@cs.purdue.edu (Christopher Emura)
  3. Newsgroups: comp.lang.c
  4. Subject: Memory Allocation (calloc()) question.
  5. Date: 24 Feb 1996 03:18:21 GMT
  6. Organization: Purdue University
  7. Message-ID: <4gm01t$spp@mozo.cc.purdue.edu>
  8. NNTP-Posting-Host: lore.cs.purdue.edu
  9. X-Newsreader: TIN [UNIX 1.3 950824BETA PL0]
  10.  
  11.  
  12. Why doesn't this section of code work?  The memory made available by
  13. calloc and pointed to by T is "saved" in A right?  No segmentation
  14. faults, just incorrect values when inserting in the "double array"
  15. block.  I.e. if the original array never needs to be doubled, this
  16. function works.
  17.  
  18.  
  19. int insert(elementType *A, elementType x,
  20.            int *currentSize, int *size, float percent) {
  21.  
  22.   /* will double array size when percent capacity is reached */
  23.  
  24.   /* check size first */
  25.   if ( *currentSize > (*size * percent) ) {
  26.     /* need to double the array */
  27.     int i;
  28.     elementType *T;
  29.  
  30.     *size = (int) *size * 2;
  31.     T = calloc(*size, sizeof(elementType));
  32.     for(i=0; i < *currentSize; i=i+1) {
  33.       T[i] = A[i];
  34.       }
  35.     fprintf(stderr,"Flag 1 trying to do %d at T[%d]\n",x,*currentSize);
  36.     T[*currentSize] = x;
  37.  
  38.     *currentSize = *currentSize + 1;
  39.     A = T;
  40.     }
  41.  
  42.   else {
  43.     /* simply insert the element */
  44.     A[*currentSize] = x;
  45.     *currentSize = *currentSize + 1;
  46.     }
  47.  
  48.   return(0);
  49.   }
  50.